package com.test.springCloud.utils;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;

import javax.servlet.http.HttpServletResponse;

import org.springframework.web.multipart.MultipartFile;

import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.serializer.SerializerFeature;

import cn.hutool.http.HttpRequest;
import cn.hutool.http.HttpResponse;

/**
* @author:LuoXingFa;
* @version:Date:2022年8月3日下午1:53:51
*/
public class Base64Upload {
	
	public String uploadBase64(String base64,HttpServletResponse response) {
		JSONObject jb = new JSONObject();
		//对图片作一个上传处理（上传base64图片）
		response.setHeader("Access-Control-Allow-Origin", "*");
	    response.setHeader("Access-Control-Allow-Methods", "*");
	    response.setHeader("Access-Control-Allow-Headers", "x-requested-with,content-type");
	    response.setContentType("application/json");
	    response.setCharacterEncoding("utf-8");
	    
		MultipartFile multipartFile = Base64ToImage.base64MultiFile(base64);
		  //判断是否有文件
          if (multipartFile.getSize()<=0) {
          	jb.put("code", 4050);
				jb.put("msg", "请至少选择一个文件上传！");
				
				return JSONObject.toJSONString(jb,SerializerFeature.WriteMapNullValue);
			}
          //判断文件名是否合格
          String originalFilename = multipartFile.getOriginalFilename();
          if (null==originalFilename||originalFilename.isEmpty()) {
				jb.put("code", 4054);
				jb.put("msg", "文件名不规范，请规范命名！");
				return JSONObject.toJSONString(jb,SerializerFeature.WriteMapNullValue);
			}
          //判断尾缀是否合格
          String substr = originalFilename.substring(originalFilename.lastIndexOf("."));
          if (!FileUtil.IMAGE_EXTENSIONS.contains(substr)) {
				jb.put("code", 4055);
				jb.put("msg", "图片文件后缀名不合格！");
				
				return JSONObject.toJSONString(jb,SerializerFeature.WriteMapNullValue);
			}
          String lastFile = null;
          String newFileName =CommonUtil.getUUid()+substr;//新文件名字
          String folderFile = /*File.separator+*/"/tamp/"/*+File.separator*/;
          String fatherFile = folderFile+DateUtil.getYMD()+"/"+DateUtil.getHH()+"/";
          //文件暂存位置
          String filePath = System.getProperty("user.dir")+/*File.separator+*/"/src/"+/*File.separator+*/"/main"
                            +/*File.separator+*/"/resources"+fatherFile;
          
          String fileUrl = null;
          File file = new File(filePath);
          if (!file.exists()) {
				file.mkdirs();
			}
          
          //文件读取流操作
          FileOutputStream fos = null;
		    try {
					lastFile = filePath+newFileName;
					fos = new FileOutputStream(lastFile);
					fos.write(multipartFile.getBytes());
						
					//写入服务器
					fileUrl = "mangerapi.yishun618.com/imgServer/uploadPlatIndexPicAndReturnImgUrl/";
			} catch (Exception e) {
				e.printStackTrace();
			}finally {
				//关闭流
				if (fos!=null) {
					try {
						fos.flush();
						fos.close();
					} catch (IOException e) {
						e.printStackTrace();
					}
				}
			}
		    HttpResponse res = HttpRequest.post(fileUrl).form("file", newFileName).execute();

			String responseStr = res.body().toString();

		MatchStrUtil parentStr = new MatchStrUtil();
			if (parentStr.parent502NetFalid(responseStr)) {
				jb.put("code", 0);
				jb.put("message", "上传图片到所请求的服务器网关出错（502服务器未开启）");
				return JSONObject.toJSONString(jb,SerializerFeature.WriteMapNullValue);
			}
		return fileUrl+newFileName;
		
	}

}
